<?php
/**
 * Este es un helper CakePHP que sirve para dar distintos tipos personalizados de formato
 */

//uses("view" . DS . "helpers" . DS . "form");  

class FormularioHelper extends AppHelper
{
	var $helpers = array('Html', 'Form', 'Ajax', 'Presentacion', 'Javascript', 'Formato');
	/**
	 * Returns an HTML FORM element.
	 *
	 * @access public
	 * @param string $model The model object which the form is being defined for
	 * @param array  $options
	 * @return string An formatted opening FORM tag.
	 */
	function create($model = null, $options = array()) {
		return $this->Form->create($model, $options);
	}


/**
 * Generates a form input element complete with label and wrapper div
 *
 * @param string $tagName This should be "Modelname.fieldname", "Modelname/fieldname" is deprecated
 * @param array $options
 * @return string
 */
	function input($tagName, $options = array()) {
		if(isset($options['type']) && $options['type'] == "checkboxMultiple") {
			return $this->checkboxMultiple($tagName, $options['options'], $options['selected']);
		}
		else {
			return $this->Form->input($tagName, $options);
		}
	}

/**
 * Creates a submit button element.
 *
 * @param  string  $caption  The label appearing on the button
 * @param  array   $options
 * @return string A HTML submit button
 */
	function submit($caption = 'Submit', $options = array()) {
		return $this->Form->submit($caption, $options);
	}

	function button($caption = '', $options = array()) {
		$return = '<div class="submit">';
		$return .= '<input type="button" ' . $this->_parseAttributes($options, null, '', '') . '>';
		$return .= '</div>';
		return $return;
	}



/**
 * Creates a set of radio widgets.
 *
 * @param  string  $fieldName Name of a field, like this "Modelname/fieldname"
 * @param  array	$options			Radio button options array
 * @param  array	$inbetween		String that separates the radio buttons.
 * @param  array	$htmlAttributes Array of HTML attributes.
 * @return string
 */
	function radio($fieldName, $options, $inbetween = null, $htmlAttributes = array()) {
		return $this->Html->radio($fieldName, $options, $inbetween, $htmlAttributes);
	}

 /**
 * Returns a formatted SELECT element.
 *
 * @param string $fieldName Name attribute of the SELECT
 * @param array $options Array of the OPTION elements (as 'value'=>'Text' pairs) to be used in the SELECT element
 * @param mixed $selected The option selected by default.  If null, the default value
 *                        from POST data will be used when available.
 * @param array $attributes  The HTML attributes of the select element.  If
 *                           'showParents' is included in the array and set to true,
 *                           an additional option element will be added for the parent
 *                           of each option group.
 * @param mixed $showEmpty If true, the empty select option is shown.  If a string,
 *                         that string is displayed as the empty element.
 * @return string Formatted SELECT element
 */
	function select($fieldName, $options = array(), $selected = null, $attributes = array(), $showEmpty = '') {
		return $this->Form->select($fieldName, $options, $selected, $attributes, $showEmpty);
	}

/**
 * Closes an HTML form.
 *
 * @access public
 * @return string A closing FORM tag.
 */
	function end($model = null) {
		return $this->Form->end($model);
	}

/**
 * Creates a password input widget.
 *
 * @param  string  $fieldName Name of a field, like this "Modelname.fieldname", "Modelname/fieldname" is deprecated
 * @param  array	$options Array of HTML attributes.
 * @return string
 */
	function password($fieldName, $options = array()) {
	return $this->Form->password($fieldName, $options);
	}

/**
 * Creates a button tag.
 *
 * @param  mixed  $params  Array of params [content, type, options] or the
 *                         content of the button.
 * @param  string $type    Type of the button (button, submit or reset).
 * @param  array  $options Array of options.
 * @return string A HTML button tag.
 * @access public
 	function button($params, $type = 'button', $options = array()) {

		$this->_parseAttributes($options
		//<button type="button" name="segundoboton">Bot&oacute;n Button</button>
	}
*/

/**
 * Returns a button input tag that will submit using Ajax
 *
 * Returns a button input tag that will submit form using XMLHttpRequest in the background instead of regular
 * reloading POST arrangement. <i>options</i> argument is the same as in <i>form_remote_tag</i>
 *
 * @param string $title Input button title
 * @param array $options Callback options
 * @return string Ajaxed input button
 */
	function submitAJAX($title = 'Submit', $options = array()) {
		return $this->Ajax->submit($title, $options);
	}

/**
 * Returns a set of SELECT elements for a full datetime setup: day, month and year, and then time.
 *
 * @param string $tagName Prefix name for the SELECT element
 * @param string $dateFormat DMY, MDY, YMD or NONE.
 * @param string $timeFormat 12, 24, NONE
 * @param string $selected Option which is selected.
 * @return string The HTML formatted OPTION element
 */
	function dateTime($tagName, $dateFormat = 'D/M/Y', $timeFormat = '24', $selected = null, $attributes = array(), $showEmpty = true) {
		return $this->Form->dateTime($tagName, $dateFormat, $timeFormat, $selected, $attributes, $showEmpty);
	}

/**
 */
	function rangoFechas($tagName, $options = array(), $separador="</td><td>", $seleccionarHora=false) {
		$options_desde = $options;
		$options_hasta = $options;
		if(isset($options['label']['text']) && !empty($options['label']['text']))
		{
			$options_desde['label']['text'] = $options['label']['text'] . " desde";
			$options_hasta['label']['text'] = $options['label']['text'] . " hasta";
			$options_desde['div'] = false;
			$options_hasta['div'] = false;
		}

		$tagNameDesde = str_replace(".", "", Inflector::camelize($tagName . "__Desde"));
		$tagNameHasta = str_replace(".", "", Inflector::camelize($tagName . "__Hasta"));

		$return = "";
		$return .= $this->inputFecha($tagName . "__desde", $options_desde, $seleccionarHora);
		$return .= $separador;
		$return .= $this->inputFecha($tagName . "__hasta", $options_hasta, $seleccionarHora);
		return $return;
	}

	function inputFecha($tagName, $options = array(), $seleccionarHora=false) {
		$this->setFormTag($tagName);
		if(!isset($options['id']))
			$id = $this->domId(implode('.', array_filter(array($this->model(), $this->field()))));
		else
			$id = $options['id'];
		$options = am($options, array("type" => "text"));
		$rnd = intval(rand());
		$codigo_html = $this->Presentacion->image("calendario.png", array("style" => "cursor: pointer;", "alt" => "Seleccione una fecha", "id" => $rnd));

		if($seleccionarHora) {
			$codigo_html .= $this->Javascript->codeBlock("
				Calendar.setup({
					inputField     :    '" . $id . "',
					ifFormat       :    '%d/%m/%Y %H:%M',	
					button         :    '" . $rnd . "',
					align          :    'Tl',
					singleClick    :    true,
					timeFormat	   :    '24',
					showsTime	   :    true
				})");
		}
		else {
			$codigo_html .= $this->Javascript->codeBlock("
				Calendar.setup({
					inputField     :    '" . $id . "',
					ifFormat       :    '%d/%m/%Y',	
					button         :    '" . $rnd . "',
					align          :    'Tl',
					singleClick    :    true
				})");
		}

		//doy formato a la fecha en caso de ser edicion
		$return = $this->input($tagName, $options);
		$inicio = strpos($return, "value=\"");
		if($inicio)
		{
			$inicio += 7;
			$fin = strpos($return, "\"", $inicio);
			if($fin)
			{
				$value = trim(substr($return, $inicio, $fin - $inicio));
				$fecha = $this->Formato->formatearFecha(trim(substr($value, 0, 10)));
				$hora = "";
				if(eregi("^[0-9]{2}:[0-9]{2}$", trim(substr($value, 11, 5)))) {
					$hora = " " .trim(substr($value, 11, 5));
				}
				//$hora = if$this->Formato->formatearFecha(trim(substr($value, 0, 10)));
				$return = str_replace($value, $fecha . $hora, $return);
				//$return = $return;
			}
		}
		return $return . $codigo_html;
	}

	function inputFechaHora($tagName, $options = array()) {
		//return $this->inputFecha($tagName, $options) . "&nbsp;" . $this->inputHora($tagName);
		return $this->inputFecha($tagName, $options, true);
	}


	function inputHora($tagName, $options = array()) {
		return $this->dateTime($tagName, 'D/M/Y', '24', null, array("class"=>"select_hora"));
	}

/**
 * Returns a list of checkboxes.
 *
 * @param string $fieldName Name attribute of the SELECT
 * @param array $options Array of the elements (as 'value'=>'Text' pairs)
 * @param array $selected Selected checkboxes
 * @param array $htmlAttributes Array of HTML options
 * @param array $containerAttributes Array of HTML attributes used for the containing tag
 * @param boolean $showEmpty If true, the empty checkbox option is shown
 * @param  boolean $return         Whether this method should return a value
 * @return string List of checkboxes
 */
    function checkboxMultiple($fieldName, $options, $selected = null, $htmlAttributes = null, $containerAttributes = array("class" => "checkboxMultiple"), $return = false) {
        if ($this->tagIsInvalid($this->model(), $this->field())) {
            if (isset($htmlAttributes['class']) && trim($htmlAttributes['class']) != "") {
                $htmlAttributes['class'] .= ' form_error';
            } else {
                $htmlAttributes['class'] = 'form_error';
            }
        }
        if (!is_array($options)) {
            return null;
        }
        if (!isset($selected)) {
            $selected = $this->Form->error($fieldName);
        }
        //if ($showEmpty === true) {
        //    $checkbox[] = sprintf($this->tags['hiddenmultiple'], $this->model(), $this->field(), $this->Html->parseHtmlOptions($htmlAttributes));
        //}
        foreach($options as $name => $title) {
	        $this->setFormTag($fieldName);
            $optionsHere = am(array("class"=>"checkbox"), $htmlAttributes);
            if (!isset($htmlAttributes['id'])) {
				$optionsHere['id'] = $this->model() . Inflector::camelize($this->field()) . $name;
            }
            $optionsHere['value'] = $name;
            if (($selected !== null) && ($selected == $name)) {
                $optionsHere['checked'] = 'checked';
            } else if (is_array($selected) && array_key_exists($name, $selected)) {
                $optionsHere['checked'] = 'checked';
            }
            $checkbox[] = "<li>" . sprintf($this->tags['checkboxmultiple'], $this->model(), $this->field(), $this->Html->_parseAttributes($optionsHere)) . $this->Form->label($optionsHere['id'], $title) . "</li>\n";
        }

		$id = mt_rand();
		$out = "";
		$out .= "<span id='acciones'>";
		$out .= $this->Html->link("Todos", "#", array("onclick"=>"accionesChecks('seleccionar', '" . $id . "');"));
		$out .= $this->Html->link("Ninguno", "#", array("onclick"=>"accionesChecks('deseleccionar', '" . $id . "');"));
		$out .= $this->Html->link("Invertir", "#", array("onclick"=>"accionesChecks('invertir', '" . $id . "');"));
		$out .= "</span>";
		$out .= "<span>";
        $out .= "\n<ul".$this->Html->_parseAttributes($containerAttributes).">\n" . $this->Html->output(implode($checkbox), $return) . "</ul>\n";
		return $this->Html->div("checkboxMultiple", $out, array("id" => $id));
		$out .= "</span>";
    } 
}

?>
